<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class contact_model extends MY_Model {

	protected $table		= "contacts";
	protected $key			= "id";
	protected $soft_deletes	= true;
	protected $date_format	= "datetime";
	protected $set_created	= true;
	protected $set_modified = true;
	
	protected $orderby 		= "name_ar";

	//---------------------------------------------------------------
	
	function find($id='')
	{
		//parent::set_selects();
		
		//check if the contact has company
		// if yes do the join else skip join
		
		$this->db->select('company');
		$isCom = $this->db->get_where($this->table, array($this->table.'.'. $this->key => $id));
		
		if($isCom->row('company')!=0){
		$this->db->select('contacts.*, company.name as com_name');
		$this->db->join('company', 'company.id = contacts.company');
		}
		$query = $this->db->get_where($this->table, array($this->table.'.'. $this->key => $id));
		
		if ($query->num_rows())
		{
			return $query->row();
		}
		
		return false;
	}

	function find_by_flag()
	{

		$this->db->select('contacts.*');
		$this->db->distinct();
		$this->db->from('contacts');
		$i = 0; 
		while($i < count($this->allowed_flags_id)){
			if($i==0)
				$this->db->where('flag.id', $this->allowed_flags_id[$i]);
			else
				$this->db->or_where('flag.id', $this->allowed_flags_id[$i]);

			$i++;
		}
		
		$this->db->join('flag_contact','flag_contact.contact_id = contacts.id');
		$this->db->join('flag','flag.id = flag_contact.flag_id');
		$query = $this->db->get();
				
		if ($query->num_rows())
		{
			return $query->result();
		}
		
		return false;

	}
}
